// 权限组名单
var $permissionManagementListTable = $('#permissionManagementList');
//防止表头与表格不对齐
$(window).resize(function () {
    $permissionManagementListTable.bootstrapTable('resetView');
});


$(function () {
    //初始化权限组名单列表
    permissionManagementListInit();
})

/**
 * 加载权限组名单列表
 */
function permissionManagementListInit() {
    //先销毁表格
    $permissionManagementListTable.bootstrapTable('destroy');
    $permissionManagementListTable.bootstrapTable({
        classes: 'table table-noborder table-hover',
        url: '/permissionManagement/getPermissionManagementList',
        method: 'post',
        //请求内容类型
        contentType: "application/x-www-form-urlencoded",
        //数据类型
        dataType: "json",
        //是否显示行间隔色
        striped: true,
        //是否启用排序
        sortable: true,
        //排序方式
        sortOrder: "desc",
        sortName: 'createTm',
        //是否使用缓存
        cache: false,
        //显示隐藏列
        showColumns: false,
        //显示刷新按钮
        showRefresh: false,
        //切换显示样式
        showToggle: false,
        //显示Table脚部
        showFooter: false,
        //是否显示分页
        pagination: true,
        //是否显示分页按钮
        showPaginationSwitch: false,
        //是否启用点击选中行
        clickToSelect: false,
        singleSelect: false,
        //最少要显示的列数
        minimumCountColumns: 2,
        //cell没有值时显示
        undefinedText: '-',
        //分页方式：client客户端分页，server服务端分页
        sidePagination: "server",
        uniqueId: 'permissionGroupId',
        idField: 'permissionGroupId',
        //每页的记录行数
        pageSize: globalPageSize,
        //初始化加载第1页，默认第1页
        pageNumber: 1,
        //可供选择的每页的行数
        pageList: globalPageList,
        //查询参数
        queryParams: queryParams,
        columns: [
            {title: '主键', field: 'permissionGroupId', visible: false},
            {title: '序号',field: 'index',align: 'left', valign: 'middle',formatter: indexFormat},
            {title: '权限组名称', field: 'permissionGroupName', align: 'left', valign: 'middle'},
            {title: '创建时间', field: 'createTm', align: 'left', valign: 'middle'},
            {title: '备注信息', field: 'remark', align: 'left', valign: 'middle',},
            {title: '操作', field: 'operate', align: 'right', valign: 'middle',
                formatter: genderOpt,  // 自定义方法
                events: {
                    'click .add-btn': function (event, value, row, index) {
                        showAddUserAccountModal(row);
                    },
                    /*'click .modify-btn': function (event, value, row, index) {
                        modify(row);
                    },*/
                    'click .del-btn': function (event, value, row, index) {
                        delPermissionGroup(row);
                    },
                    'click .show-btn': function (event, value, row, index) {
                        //详情
                        parent.$(parent.document).data('multitabs').create({
                            iframe : true,
                            title : '权限组详情',
                            url : '/permissionManagement/permissionGroupDetail?permissionGroupId='+row.permissionGroupId
                        }, true);
                    }

                }
            }
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                window.location.reload();
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        }, formatNoMatches: function () {
            return '无符合条件的记录';
        }
    });
}

function indexFormat(value, row, index) {
    return index + 1;
}

function queryParams(params) {
    //搜索条件
    params.permissionGroupName= $('#searchInfo').val();
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    return params;
}

// 操作
function genderOpt(value, row, index) {
    var isAdmin = row.isAdmin;
    console.log(isAdmin);
    let add = '<a class="btn m-r-5 add-btn" href="#!" title="添加人员" data-toggle="tooltip" data-original-title="添加人员"><i class="mdi mdi-plus"></i></a>';
    //let modify = '<a style="margin-right: 6px;" class="btn btn-xs btn-default" href="#!" title="编辑" data-toggle="tooltip" data-original-title="编辑"><i class="mdi mdi-pencil"></i></a>';
    let view ='<a class="btn m-r-5 show-btn" href="#!" title="详情" data-toggle="tooltip" data-original-title="详情"><i class="mdi mdi-eye"></i></a>';
    let del ='<a class="btn del-btn" href="#!" title="删除" data-toggle="tooltip" data-original-title="删除"><i class="mdi mdi-window-close"></i></a>';
    let html;
    if(isAdmin == 0){
        html = add + view + del;
    } else {
        html = add;
    }
    return html;
}

/**
 * 展示添加人员模态框
 * @param row
 */
function showAddUserAccountModal(row) {
    var permissionGroupId = row.permissionGroupId;
    $.post('/permissionManagement/whetherHavePermission',{permissionGroupId:permissionGroupId},function(data) {
        if (data != null) {
            if (data.data == false) {
                $.alert({
                    title: '温馨提示',
                    content: '没有权限',
                });
                return ;
            } else {
                var zNodes;
                var setting = {
                    view: {
                        showLine: true,//显示节点之间的连线。
                        selectedMulti: false  //允许同时选中多个节点。
                    },
                    data: {
                        simpleData: {
                            enable: true,
                            idKey: "id",
                            pIdKey: "pId",
                            rootPId: 0
                        }
                    },
                    check: {
                        enable: true
                    }
                };
                $.ajax({
                    type:"post",
                    url:"/account/getPermissionAccountList",
                    data:{
                        "permissionGroupId" : permissionGroupId
                    },
                    dataType:"json",
                    success:function(data){
                        if (data.code == '000000') {
                            zNodes=data.data;
                            console.log(zNodes);
                            $.fn.zTree.init($("#accountTree"), setting, zNodes);
                            /*var treeObj=$.fn.zTree.getZTreeObj("accountTree"),
                                nodes=treeObj.getCheckedNodes(true);
                            if (nodes.length>0) {
                                for(var i=0;i<nodes.length;i++){
                                    var parentNode = nodes[i].getParentNode();
                                    treeObj.expandNode(parentNode, true, false, false);
                                }
                            }*/
                        } else {
                            $.alert({
                                title: '温馨提示',
                                content: '加载失败',
                            });
                        }
                    }
                });
                $("#permissionGroupId").val(row.permissionGroupId);
                $('#addUserAccountModal').modal('show');
            }
        }
    });
}

/**
 * 删除权限组
 * @param row
 */
function delPermissionGroup(row) {
    $.confirm({
        title: '温馨提示',
        content: '确认要删除?',
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action:function(){
                    $.ajax({
                        url: "/permissionManagement/delPermissionGroup",
                        method: 'post',
                        data: {
                            "permissionGroupId": row.permissionGroupId
                        },
                        success: function (data) {
                            if (data.code == '000000') {
                                $.alert({
                                    title: '温馨提示',
                                    content: '删除成功',
                                    buttons: {
                                        confirm: {
                                            text: '确认',
                                            btnClass: 'btn-primary',
                                            action: function () {
                                                window.location.reload();
                                            }
                                        }
                                    }
                                });
                            } else {
                                $.alert({
                                    title: '温馨提示',
                                    content: '删除失败'
                                });
                            }
                        }
                    });}
            },
            cancel: {
                text: '取消'
            }
        }
    });

}

/**
 * 保存账号-权限组关联
 */
function saveAccountPermission(){
    var permissionGroupId = $("#permissionGroupId").val();
    var treeObj=$.fn.zTree.getZTreeObj("accountTree"),
        nodes=treeObj.getCheckedNodes(true);
    var accountIds = [];
    if (nodes.length>0) {
        for(var i=0;i<nodes.length;i++){
            accountIds.push({"id":nodes[i].id,"pId":nodes[i].pId,"name":nodes[i].name,"accountIdentification":nodes[i].accountIdentification});
        }
    } /*else {
        $.alert({
            title: '温馨提示',
            content: '请勾选账号！',
        });
        return ;
    }*/
    $.confirm({
        title: '温馨提示',
        content: '确认要保存?',
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function(){
                    $.ajax({
                        type: "post",
                        url: "/permissionManagement/saveAccountPermission",
                        dataType: "json",
                        data: {
                            "permissionGroupId": permissionGroupId,
                            "accountIds": JSON.stringify(accountIds)
                        },
                        success: function (data) {
                            if (data.code == '000000') {
                                $.alert({
                                    title: '温馨提示',
                                    content: '保存成功！',
                                    buttons: {
                                        confirm: {
                                            text: '确认',
                                            btnClass: 'btn-primary',
                                            action: function () {
                                                $('#addUserAccountModal').modal('hide');
                                            }
                                        }
                                    }
                                });
                            } else {
                                $.alert({
                                    title: '温馨提示',
                                    content: '保存失败,请稍后再试！'
                                });
                            }
                        },
                        error: function () {
                            $.alert({
                                title: '温馨提示',
                                content: '保存异常,请稍后再试！'
                            });
                        }
                    });
                }
            },
            cancel: {
                text: '取消'
            }
        }
    });
}
